//
//  AccountSetViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/5/27.
//

#import "AccountSetViewController.h"
#import "BindPhoneViewController.h"
#import "LogoutViewController.h"
#import "LogoutManager.h"
#import "LoginViewController.h"

@interface AccountSetViewController ()<JPAPIManagerCallBackDelegate>
@property(nonatomic,strong)LogoutManager *logoutManager;
@property(nonatomic,strong)UILabel *phoneLabel;
@end

@implementation AccountSetViewController

-(LogoutManager *)logoutManager{
    if(!_logoutManager){
        _logoutManager = [[LogoutManager alloc]init];
        _logoutManager.delegate = self;
    }
    return _logoutManager;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    [self createUI];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(phoneUpdate:) name:@"phoneUpdate" object:nil];
}

#pragma mark - 手机更新
-(void)phoneUpdate:(NSNotification*)notifi{
    if(notifi.object){
        self.phoneLabel.text = [self hideMiddleDigits:notifi.object];
    }
}

-(void)createUI{
    
    [self.customNavigationBar setTitle:@"账号设置"];
    
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 10;
    bgView.layer.masksToBounds = YES;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+20);
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        if(isIPAD){
            make.height.mas_equalTo(@116);
        }else{
            make.height.mas_equalTo(kWFit(116));
        }
    }];
    
    __weak typeof(self)self_weak_ = self;
    NSArray *arr = @[@"手机号码",@"注销账号"];
    for(NSInteger i = 0;i < arr.count;i++){
        UIView *bView = [[UIView alloc]initWithFrame:CGRectMake(0,i*kWFit(63), kScreenWidth-32,kWFit(53))];
        if(isIPAD){
            bView.frame = CGRectMake(0,i*63, self.currentAvailableWidth-32,53);
        }
        bView.tag = 100+i;
        [bgView addSubview:bView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
//            NSString *loginMode = [[NSUserDefaults standardUserDefaults]objectForKey:@"loginMode"];
//            if(loginMode&&[loginMode isEqualToString:@"4"]){
//                [self_weak_ login];
//            }else{
                if(i == 0){
                    BindPhoneViewController *vc = [[BindPhoneViewController alloc]init];
                    vc.type = 0;
                    [self_weak_.navigationController pushViewController:vc animated:YES];
                }else if (i == 1){
                    NSString *phone = [[NSUserDefaults standardUserDefaults]objectForKey:@"phone"];
                    if(phone){
                        LogoutViewController *vc = [[LogoutViewController alloc]init];
                        [self_weak_.navigationController pushViewController:vc animated:YES];
                    }else{
                        [JPProgressHUD showMsg:@"请先绑定手机号"];
                    }
                }
//            }
        }];
        [bView addGestureRecognizer:tap];
        UILabel *titleLabel = [[UILabel alloc]init];
        titleLabel.font = JPUIFontPingFangSCMedium(15);
        titleLabel.textColor = KFontBlackColor;
        titleLabel.text = arr[i];
        titleLabel.userInteractionEnabled = YES;
        [bView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(@16);
            make.height.mas_equalTo(@21);
            make.centerY.mas_equalTo(bView);
        }];
        UIImageView *arrowImageView = [[UIImageView alloc]init];
        arrowImageView.image = [UIImage imageNamed:@"mine_right_arrow"];
        arrowImageView.userInteractionEnabled = YES;
        arrowImageView.tag = 200+i;
        [bView addSubview:arrowImageView];
        [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(@-12);
            make.width.height.mas_equalTo(@16);
            make.centerY.mas_equalTo(bView);
        }];
        if (i == 0){
            UILabel *numLabel = [[UILabel alloc]init];
            numLabel.font = JPUIFontPingFangSCRegular(14);
            numLabel.textColor = KFontGrayColor;
            numLabel.textAlignment = NSTextAlignmentRight;
            NSString *phone = [[NSUserDefaults standardUserDefaults]objectForKey:@"phone"];
            if(phone){
                numLabel.text = [self hideMiddleDigits:phone];
            }
            [bView addSubview:numLabel];
            [numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(@-32);
                make.height.mas_equalTo(@21);
                make.centerY.mas_equalTo(bView);
            }];
            self.phoneLabel = numLabel;
        }
    }
    
    UIButton *logoutBtn = [[UIButton alloc]init];
    [logoutBtn setTitle:@"退出账号" forState:UIControlStateNormal];
    [logoutBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    logoutBtn.titleLabel.font = JPUIFontPingFangSCMedium(14);
    logoutBtn.backgroundColor = KThemeColor;
    if(isIPAD){
        logoutBtn.layer.cornerRadius = 49/2.0;
    }else{
        logoutBtn.layer.cornerRadius = kWFit(49)/2.0;
    }
    logoutBtn.layer.masksToBounds = YES;
    logoutBtn.ym_acceptEventInterval = 2.0;
    [logoutBtn addTarget:self action:@selector(logoutBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:logoutBtn];
    [logoutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.top.mas_equalTo(bgView.mas_bottom).offset(20);
        if(isIPAD){
            make.height.mas_equalTo(49);
        }else{
            make.height.mas_equalTo(kWFit(49));
        }
    }];
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 获取当前可用宽度并更新布局
        self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
        self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
        self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
        for(NSInteger i = 0;i < 2;i++){
            UIView *bView = [self.view viewWithTag:100+i];
            bView.frame = CGRectMake(0,i*63, self.currentAvailableWidth-32,53);
            UIImageView *arrowImageView = [bView viewWithTag:200+i];
            [arrowImageView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(@-12);
                make.centerY.mas_equalTo(bView);
            }];
            if (i==0){
                [self.phoneLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.right.mas_equalTo(@-32);
                    make.centerY.mas_equalTo(bView);
                }];
            }
        }
           
        });
    }
}

#pragma mark - 登录
-(void)login{
    LoginViewController *vc = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 退出账号
-(void)logoutBtnClick{
    [self.logoutManager loadData];
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.logoutManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        [[NSNotificationCenter defaultCenter]postNotificationName:@"logoutSuccess" object:nil];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}



-(NSString*)hideMiddleDigits:(NSString*)phoneNumber{
     NSString *maskedNumber = phoneNumber;
     if (phoneNumber.length == 13||phoneNumber.length == 11) {
         // 中国手机号码 86+11位
         // 台湾手机号码 886 +10 位
         // 香港、澳门手机号码 852+8位 853+8位
         // 日本手机号码 81+11位
         NSRange range = NSMakeRange(5,4);
         maskedNumber = [phoneNumber stringByReplacingCharactersInRange:range withString:@"****"];
     }else if (phoneNumber.length == 12) {
         // 香港手机号码 852+9位
         NSRange range = NSMakeRange(6,4);
         maskedNumber = [phoneNumber stringByReplacingCharactersInRange:range withString:@"****"];
     }
     return maskedNumber;
}



@end
